package com.controller;

import java.io.File;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.entity.Subject;
import com.entity.Sysuser;
import com.entity.TongJi;
import com.server.SubjectServer;
import com.server.ClazzServer;
import com.server.CourseServer;
import com.server.PtypeServer;
import com.server.RecordServer;
import com.server.SysuserServer;
import com.util.PageBean;

import net.sf.json.JSONObject;

@Controller
public class SubjectController {
	@Resource
	private SubjectServer subjectService;
	@Resource
	private CourseServer courseService;
	@Resource
	private ClazzServer clazzService;
	@Resource
	private SysuserServer userService;
	@Resource
	private RecordServer recordService;
	@Resource
	private PtypeServer ptypeService;

	/**
	 * 同一培训师本学年评价得分上学年评价得分作对比（一学期教师多条评价的平均分与上学期平均分作对比））
	 * 
	 * @param request
	 * @param Subject
	 * @param session
	 * @return
	 */

	@RequestMapping("admin/doTeacherTj.do")
	public String doTeacherTj(ModelMap map) {
		Map<String, Object> tmap = new HashMap<>();
		tmap.put("utype", "培训师");
		map.put("tlist", userService.getAll(tmap));
		return "admin/tj_term";
	}

	// 统计分析
	@RequestMapping("admin/tj_term.do")
	public void tj_term(ModelMap map, int id, HttpSession session, HttpServletResponse response) {
		Map<String, Object> cmap = new HashMap<String, Object>();
		cmap.put("id", id);
		List<TongJi> tjlist = userService.getTongJi(cmap);
		System.out.println("aaaaaaaaaaa==" + tjlist.size());
		String stu = "[";
		String account = "[";
		for (TongJi tj : tjlist) {

			stu += "'" + tj.getName() + "',";
			account += "" + tj.getAmount() + ",";
		}
		int n = stu.length();
		stu = stu.substring(0, n - 1);
		int n2 = account.length();
		account = account.substring(0, n2 - 1);
		stu += "]";
		account += "]";
		System.out.println(stu);
		System.out.println(account);
		JSONObject obj = new JSONObject();
		obj.put("stu", stu);
		obj.put("account", account);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(obj);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}

	/**
	 * 本学年评价得分和职员实验课成绩得分和教师自我评价得分作对比（职员每一节课后给培训师打得分）
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("admin/doTeacherTj_ben.do")
	public String doTeacherTj_ben(ModelMap map) {
		Map<String, Object> tmap = new HashMap<>();
		tmap.put("utype", "培训师");
		map.put("tlist", userService.getAll(tmap));
		return "admin/tj_term_ben";
	}
	// 统计分析
		@RequestMapping("admin/tj_term_ben.do")
		public void tj_term_ben(ModelMap map, int id, HttpSession session, HttpServletResponse response) {
			Map<String, Object> cmap = new HashMap<String, Object>();
			cmap.put("uid", id);
			List<TongJi> tjlist = subjectService.getTongJi(cmap);
			System.out.println("aaaaaaaaaaa==" + tjlist.size());
			String name = "[";
			String account = "[";
			String scope1 = "[";
			String scope2 = "[";
			for (TongJi tj : tjlist) {

				name += "'" + tj.getName() + "',";
				scope1 += "'" + tj.getScope1() + "',";
				scope2 += "'" + tj.getScope2() + "',";
				account += "" + tj.getScope3() + ",";
			}
			int n = name.length();
			name = name.substring(0, n - 1);
			int n2 = account.length();
			account = account.substring(0, n2 - 1);
			int n3 = scope1.length();
			scope1 = scope1.substring(0, n3 - 1);
			int n4 = scope2.length();
			scope2 = scope2.substring(0, n4 - 1);
			name += "]";
			account += "]";
			scope1 += "]";
			scope2 += "]";
			System.out.println(name);
			System.out.println(scope1);
			System.out.println(scope2);
			System.out.println(account);
			JSONObject obj = new JSONObject();
			obj.put("name", name);
			obj.put("scope1", scope1);
			obj.put("scope2", scope2);
			obj.put("account", account);
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.print(obj);
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				out.close();
			}
		}

	
	/**
	 * 同一实验课不同培训师上课评价得分对比（职员每一节课后给培训师打得分））
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("admin/doTeacherTj_kc.do")
	public String doTeacherTj_kc(ModelMap map) {
		Map<String, Object> tmap = new HashMap<>();
		tmap.put("utype", "培训师");
		map.put("clist", courseService.getAll(null));
		return "admin/tj_term_kc";
	}

	// 统计分析
	@RequestMapping("admin/tj_term_kc.do")
	public void tj_term_kc(ModelMap map, int id, HttpSession session, HttpServletResponse response) {
		Map<String, Object> cmap = new HashMap<String, Object>();
		cmap.put("cid", id);
		List<TongJi> tjlist = subjectService.getTongJi_kc(cmap);
		System.out.println("aaaaaaaaaaa==" + tjlist.size());
		String name = "[";
		String account = "[";
		String scope1 = "[";
		for (TongJi tj : tjlist) {

			name += "" + tj.getName() + ",";
			scope1 += "'" + tj.getScope1() + "',";
			account += "'" + tj.getScope2() + "',";
		}
		int n = name.length();
		name = name.substring(0, n - 1);
		int n2 = account.length();
		account = account.substring(0, n2 - 1);
		int n3 = scope1.length();
		scope1 = scope1.substring(0, n3 - 1);
		name += "]";
		account += "]";
		scope1 += "]";
		System.out.println(name);
		System.out.println(account);
		System.out.println(scope1);
		JSONObject obj = new JSONObject();
		obj.put("name", name);
		obj.put("scope1", scope1);
		obj.put("account", account);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(obj);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}

	

	// 添加课节
	@RequestMapping("admin/addSubject.do")
	public String addSubject(HttpServletRequest request, Subject Subject, HttpSession session) {
		System.out.println("ddddd");
		Sysuser u = (Sysuser) session.getAttribute("auser");
		System.out.println("u=-=" + u);
		if (u == null || u.equals("")) {
			return "admin/login";
		} else {
			java.sql.Timestamp time = new Timestamp(System.currentTimeMillis());
			Subject.setPubtime(time.toString().substring(0, 19));
			Subject.setIsdel("1");

			Subject.setGid(u.getGid());
			Subject.setCid(u.getCid());
			Subject.setStype("课节");
			Subject.setStatus("待评价");
			Subject.setTeaPj(0.0);
			Subject.setStuPj(0.0);
			Subject.setUid(u.getId());
			subjectService.add(Subject);
			Map<String, Object> smap = new HashMap<>();
			smap.put("stype", "课节");
			smap.put("uid", u.getId());
			List<Subject> slist = subjectService.getAll(smap);
			double avg = 0.0;
			int account = subjectService.getCount(smap);
			for (Subject sub : slist) {
				avg += sub.getZiPj();
			}
			avg = avg / account;
			Map<String, Object> kmap = new HashMap<>();
			kmap.put("stype", "课程");
			kmap.put("uid", u.getId());
			List<Subject> klist = subjectService.getAll(kmap);
			Subject sub = klist.get(0);
			sub.setZiPj(avg);
			subjectService.update(sub);
			return "admin/success";
		}
	}

	@RequestMapping("admin/doUpdateSubject.do")
	public String doUpdateSubject(ModelMap map, int id) {
		map.put("jz", subjectService.getById(id));
		return "admin/subject_update";
	}

	@RequestMapping("admin/updateSubject.do")
	public String updateSubject(HttpServletRequest request, Subject Subject) {
		Subject ss = subjectService.getById(Subject.getId());
		subjectService.update(Subject);
		Map<String, Object> smap = new HashMap<>();
		smap.put("stype", "课节");
		smap.put("uid", ss.getUid());
		List<Subject> slist = subjectService.getAll(smap);
		double avg = 0.0;
		int account = subjectService.getCount(smap);
		for (Subject sub : slist) {
			avg += sub.getZiPj();
		}
		avg = avg / account;
		Map<String, Object> kmap = new HashMap<>();
		kmap.put("stype", "课程");
		kmap.put("uid", ss.getUid());
		List<Subject> klist = subjectService.getAll(kmap);
		Subject sub = klist.get(0);
		sub.setZiPj(avg);
		subjectService.update(sub);
		return "admin/success";
	}

	// 课节详情
	@RequestMapping("admin/showSubjectx.do")
	public String showSubject(ModelMap map, int id, HttpSession session) {
		Sysuser user = (Sysuser) session.getAttribute("auser");
		if (user == null) {
			return "admin/login";
		} else {
			Map<String, Object> smap = new HashMap<>();
			smap.put("uid", user.getId());
			smap.put("sid", id);
			int count = recordService.getCount(smap);
			if (count > 0) {
				session.setAttribute("info", "你已评价过该课节！");
				return "admin/error";
			} else {
				map.put("plist", ptypeService.getAll(null));
				map.put("jz", subjectService.getById(id));
				return "admin/subjectx";
			}
		}

	}

	// 分页查询
	@RequestMapping("admin/subjectList.do")
	public String jianList(@RequestParam(value = "page", required = false) String page, ModelMap map,
			HttpSession session) {
		Sysuser u = (Sysuser) session.getAttribute("auser");
		System.out.println("u=-=" + u);
		if (u == null || u.equals("")) {
			return "admin/login";
		} else {
			if (page == null || page.equals("")) {
				page = "1";
			}
			PageBean pageBean = new PageBean(Integer.parseInt(page), PageBean.PAGESIZE);
			Map<String, Object> pmap = new HashMap<String, Object>();
			pmap.put("pageno", pageBean.getStart());
			pmap.put("pageSize", pageBean.getPageSize());
			Map<String, Object> cmap = new HashMap<String, Object>();
			if (u.getUtype().equals("培训师")) {
				cmap.put("uid", u.getId());
				pmap.put("uid", u.getId());
			} else if (u.getUtype().equals("职员")) {
				cmap.put("gid", u.getGid());
				pmap.put("gid", u.getGid());
			} else {
				cmap.put("gid", null);
				pmap.put("gid", null);
			}
			cmap.put("stype", "课节");
			pmap.put("stype", "课节");
			Map<String, Object> kmap = new HashMap<>();
			kmap.put("stype", "课程");
			kmap.put("uid", u.getId());
			int total = subjectService.getCount(cmap);
			if (u.getUtype().equals("培训师")) {
				int num = subjectService.getCount(kmap);
				if (num == 0) {
					Timestamp time = new Timestamp(System.currentTimeMillis());
					Subject sub = new Subject();
					sub.setCid(u.getCid());
					sub.setIsdel("1");
					sub.setPubtime(time.toString().substring(0, 19));
					sub.setGid(u.getGid());
					sub.setStype("课程");
					sub.setUid(u.getId());
					subjectService.add(sub);
				}
			}
			pageBean.setTotal(total);
			List<Subject> list = subjectService.getByPage(pmap);
			map.put("page", pageBean);
			map.put("list", list);
			session.setAttribute("p", 1);
			map.put("ulist", userService.getAll(null));
			map.put("glist", clazzService.getAll(null));
			map.put("clist", courseService.getAll(null));
			return "admin/subject_list";
		}
	}

	// 分页查询---职员查看课程
	@RequestMapping("admin/subjectList_kc.do")
	public String subjectList_kc(@RequestParam(value = "page", required = false) String page, ModelMap map,
			HttpSession session) {
		Sysuser u = (Sysuser) session.getAttribute("auser");
		System.out.println("u=-=" + u);
		if (u == null || u.equals("")) {
			return "admin/login";
		} else {
			if (page == null || page.equals("")) {
				page = "1";
			}
			PageBean pageBean = new PageBean(Integer.parseInt(page), PageBean.PAGESIZE);
			Map<String, Object> pmap = new HashMap<String, Object>();
			pmap.put("pageno", pageBean.getStart());
			pmap.put("pageSize", pageBean.getPageSize());
			Map<String, Object> cmap = new HashMap<String, Object>();
			if (u.getUtype().equals("培训师")) {
				cmap.put("uid", u.getId());
				pmap.put("uid", u.getId());
			} else if (u.getUtype().equals("职员")) {
				cmap.put("gid", u.getGid());
				pmap.put("gid", u.getGid());
			} else {
				cmap.put("gid", null);
				pmap.put("gid", null);
			}
			cmap.put("stype", "课程");
			pmap.put("stype", "课程");
			int total = subjectService.getCount(cmap);
			pageBean.setTotal(total);
			List<Subject> list = subjectService.getByPage(pmap);
			map.put("page", pageBean);
			map.put("list", list);
			session.setAttribute("p", 1);
			map.put("ulist", userService.getAll(null));
			map.put("glist", clazzService.getAll(null));
			map.put("clist", courseService.getAll(null));
			return "admin/subject_list_kc";
		}
	}

	// 分页模糊查询
	@RequestMapping("admin/vagueSubjectList.do")
	public String vagueSubjectList(@RequestParam(value = "page", required = false) String page, ModelMap map,
			HttpSession session, Subject cd) {
		if (page == null || page.equals("")) {
			page = "1";
		}
		PageBean pageBean = new PageBean(Integer.parseInt(page), PageBean.PAGESIZE);
		Map<String, Object> pmap = new HashMap<String, Object>();
		pmap.put("pageno", pageBean.getStart());
		pmap.put("pageSize", pageBean.getPageSize());

		Map<String, Object> cmap = new HashMap<String, Object>();
		if (cd.getName() != null && !cd.getName().equals("")) {
			cmap.put("name", cd.getName());
			pmap.put("name", cd.getName());
		}
		cmap.put("stype", "课节");
		pmap.put("stype", "课节");
		int total = subjectService.getCount(cmap);
		pageBean.setTotal(total);
		List<Subject> list = subjectService.getByPage(pmap);
		map.put("page", pageBean);
		map.put("list", list);
		session.setAttribute("p", 2);
		map.put("ulist", userService.getAll(null));
		map.put("glist", clazzService.getAll(null));
		map.put("clist", courseService.getAll(null));
		return "admin/subject_list";
	}

	@RequestMapping("admin/deleteSubject.do")
	public String deleteSubject(int id) {
		/*Map<String, Object> rmap = new HashMap<>();
		int count = 0;
		rmap.put("gid", id);
		count = recordService.getCount(rmap);
		if (count > 0) {
			return "admin/error_subject";
		} else {*/
			subjectService.delete(id);
			return "redirect:subjectList.do";
		/*}*/

	}

	// 文件上传
	public String fileUpload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, String img) {
		String path = request.getSession().getServletContext().getRealPath("upload");
		String fileName = file.getOriginalFilename();
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String pa = request.getContextPath() + "/upload/" + fileName;
		System.out.println("path===" + pa);
		if (fileName != null && !fileName.equals("")) {
			img = fileName;
		} else {
			img = "zanwu.jpg";
		}
		return img;

	}

}
